package com.jh.fcsm.service.inf.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jh.fcsm.beans.inf.InfApp;
import com.jh.fcsm.beans.inf.InfTask;
import com.jh.fcsm.beans.inf.vo.PlatformRequestVo;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.dao.inf.ThreePartyMapper;
import com.jh.fcsm.service.inf.InfAppService;
import com.jh.fcsm.service.inf.ThreePartyService;
import com.jh.fcsm.util.security.RSAEncrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;

@Service
@Validated
@Transactional(readOnly = true)
public class ThreePartyServiceImpl implements ThreePartyService {

	@Autowired
	private InfAppService infAppService;

	@Autowired
	private ThreePartyMapper threePartyMapper;

	/**
	 * 验证请求参数
	 * @param request
	 * @return
	 * @throws ServiceException
	 */
	@Override
	public InfApp checkRequest(@Valid PlatformRequestVo request) {
		//1.验证null
		if(request==null) {
			throw new ServiceException("非法请求");
		}
		// 3.验证加密公钥和method
		InfApp app= infAppService.findPrivateKey(request.getAppKey());
		String str = "";
		try {
			str = RSAEncrypt.privateKeyDecrypt( request.getSign(),app.getAppSecret());
			request.setMethod(str.split("@")[0]);
		} catch (Exception e) {
			throw new ServiceException("签名错误 sign=hash256(timeAffix)");
		}
		infAppService.checkMethod(request.getAppKey(),request.getMethod());
		//4.时间缀不能大于10分钟误差
		long reqTime;
		try{
			reqTime = Long.parseLong(str.split("@")[1]);
		}catch (Exception e){
			throw new ServiceException("时间戳有误");
		}
		long localDatetime = System.currentTimeMillis()/1000;
		if (Math.abs(localDatetime - reqTime) > 10 * 60) {
			throw new ServiceException("时间误差大于10分钟");
		}
		
		return app;
	}

	/**
	 * 插入数据库提交事务并返回影响行数
	 */
	@Override
	@Transactional(readOnly = false)
	public int execMethodTask(JSONArray data, List<InfTask> taskList) {
		int rows=0;
		try {
			
			for(InfTask task:taskList) {
				JSONObject obj=new JSONObject();
				obj.put("myQsql", task.getScriptCode());
				obj.put("datas", data);
				rows+=threePartyMapper.insertDynamicList(obj);
			}
		}catch(Exception e) {
			throw new ServiceException("执行插入数据失败");
		}
		return rows;
	}
}
